package com.suwenhao.controller;

import com.alibaba.fastjson.JSONObject;
import com.suwenhao.entity.Menu;
import com.suwenhao.entity.User;
import com.suwenhao.service.MenuService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author:suwenhao
 * @Description: 测试
 * @Date: Created in 2020/9/22 17:35
 */

@WebServlet("/menu/*")
public class MenuServlet extends BaseServlet {

    private MenuService menuService = new MenuService();

    protected void listAll(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        List<Menu> list = menuService.listAll();

        List<Menu> parentList = new ArrayList<>();
        List<Menu> sonList = new ArrayList<>();

        parentList = list.stream().filter(n -> {
            return n.getType().equals("1");
        }).collect(Collectors.toList());

        sonList = list.stream().filter(n->{
            return n.getType().equals("2");
        }).collect(Collectors.toList());

//        for (int i = 0; i < list.size(); i++) {
//            if (list.get(i).getType().equals("1")) {
//                parentList.add(list.get(i));
//            }
//            if (list.get(i).getType().equals("2")) {
//                sonList.add(list.get(i));
//            }
//        }


        Map<String, List<Menu>> map = new HashMap<>();
        map.put("parent", parentList);
        map.put("son", sonList);
        resp.getWriter().write(JSONObject.toJSONString(map));



    }
//    protected void listAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        List<Menu>list=menuService.listAll();
//        //方式一
//        String jsonString = JSONObject.toJSONString(list);
//        //方式er
//       ObjectMapper om=new ObjectMapper();
//       String jsonString2 = om.writeValueAsString(list);
//
//        resp.getWriter().write(jsonString);
//    }
}


